package com.gqr.threadobjectclasscommonmethods;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:WaitNotifyPrintOddEvenSync
 * author:guqingrong
 * Date:2024-04-23 21:35
 * Description:两个线程交替打印0-100奇偶数,用synchronized实现
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class WaitNotifyPrintOddEvenSync {
    private static int count;
    private static final Object lock = new Object();

    // 新建两个线程
    // 1个只处理偶数 第二个只处理奇数 (用位运算)
    // 用synchronized来通信
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100){
                    synchronized (lock){
                        if((count & 1)==0){
                            System.out.println(Thread.currentThread().getName()+":"+count);
                            count++;
                        }
                    }
                }
            }
        },"偶数").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100){
                    synchronized (lock){
                        if((count & 1)==1){
                            System.out.println(Thread.currentThread().getName()+":"+count);
                            count++;
                        }
                    }
                }
            }
        },"奇数").start();
    }
}
